import { useMemo } from 'react';
import { get, isArray, isNil } from 'lodash-es';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';

import { useLatest, useMemoizedFn, useSetState } from '@/hooks';
import { useEnvSettings } from '../../store';
import { generateGroupId, internalDispatcher, InternalFields } from '../../register';

const SearchWidgetGroupFilterField = 'widgetGroupFilter';

export const useWidgetState = (option: { widgetSubscribe: any; groupFilterId: any; dispatch: any }) => {
    const { enableSearchGroupFilter } = useEnvSettings();
    const searchParams = useSearchParams();
    const pathname = usePathname();
    const router = useRouter();

    const currentState = useMemo(() => {
        return {
            searchWidgetGroupFilter: enableSearchGroupFilter ? searchParams.get(SearchWidgetGroupFilterField) : '',
        };
    }, [searchParams, enableSearchGroupFilter]);

    const latest = useLatest({ ...option, enableSearchGroupFilter });

    const showWidgetGroup = useMemoizedFn((params: { groupFilterId: any }) => {
        if (enableSearchGroupFilter) {
            const nextSearchParams = new URLSearchParams(searchParams.toString());
            nextSearchParams.set(SearchWidgetGroupFilterField, params.groupFilterId);
            router.push(`${pathname}?${nextSearchParams.toString()}`);
        } else {
            internalDispatcher.widgetGroupVisibleFilter({ dispatch: option.dispatch }, [params.groupFilterId]);
        }
    });

    const widgetVisible = useMemo(() => {
        const widgetSubscribe = option.widgetSubscribe;
        let groupFilter = latest.current.enableSearchGroupFilter
            ? [currentState.searchWidgetGroupFilter]
            : widgetSubscribe[InternalFields.WIDGET_GROUP_VISIBLE_FILTER];

        let widgetItemVisible = get(widgetSubscribe, InternalFields.WIDGET_VISIBLE, true);

        if (!isNil(groupFilter) && isArray(groupFilter)) {
            widgetItemVisible = [...new Set([...groupFilter, 'default'])]
                .map((v) => generateGroupId(v))
                .some((id) => id === latest.current.groupFilterId);
        }

        return widgetItemVisible;
    }, [option.widgetSubscribe, latest, currentState]);

    return useMemo(() => {
        return { widgetVisible, showWidgetGroup };
    }, [widgetVisible, showWidgetGroup]);
};
